import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import layout from '@/layout/index.vue'
import store from '@/store/index'
// 路由配置规则
const routes: Array<RouteRecordRaw> = [
  {
    name: 'login',
    path: '/login',
    component: () => import(/* webpackChunkName: 'login' */ '@/views/login/index.vue')
  },
  {
    path: '/',
    component: layout,
    children: [
      {
        name: 'home',
        path: '',
        component: () => import(/* webpackChunkName: 'home' */ '@/views/home/index.vue')
      },
      {
        name: 'user',
        path: '/user',
        component: () => import(/* webpackChunkName: 'user' */ '@/views/user/index.vue')
      },
      {
        name: 'course',
        path: '/course',
        component: () => import(/* webpackChunkName: 'course' */ '@/views/course/index.vue')
      },
      {
        name: 'role',
        path: '/role',
        component: () => import(/* webpackChunkName: 'role' */ '@/views/role/index.vue')
      },
      {
        name: 'menu',
        path: '/menu',
        component: () => import(/* webpackChunkName: 'menu' */ '@/views/menu/index.vue')
      },
      {
        name: 'resource',
        path: '/resource',
        component: () => import(/* webpackChunkName: 'resource' */ '@/views/resource/index.vue')
      },
      {
        name: 'advert',
        path: '/advert',
        component: () => import(/* webpackChunkName: 'advert' */ '@/views/advert/index.vue')
      },
      {
        name: 'menu-add',
        path: '/menu/add',
        component: () => import(/* webpackChunkName: 'menu' */ '@/views/menu/create.vue')
      },
      {
        name: 'menu-edit',
        path: '/menu/:id/edit',
        component: () => import(/* webpackChunkName: 'menu' */ '@/views/menu/edit.vue')
      }
    ]
  },
  {
    name: '404',
    path: '/:catchAll(.*)',
    component: () => import(/* webpackChunkName: 'advert' */ '@/views/errorPage/404.vue')
  }
]
const router = createRouter({
  history: createWebHashHistory(),
  routes
})

const whiteList = ['login', '404']

router.beforeEach((to, from, next) => {
  if (whiteList.includes(to.name as string)) {
    next()
  } else {
    if (store.state.user) {
      next()
    } else {
      next({
        name: 'login',
        query: {
          redirect: to.fullPath // 参数需要加上返回的页面路由
        }
      })
    }
  }
})

export default router
